package com.cheng.io.buffer;

import java.io.*;

public class BufferedInputStreamTest01 {
    public static void main(String[] args) {
        method2();
    }

    private void method1() {
        BufferedInputStream bufferedInputStream = null;
        try {
            // InputStream为节点流
            InputStream inputStream = new FileInputStream("io/resources/特性.txt");
            // BufferedInputStream为缓冲流，又叫处理流、包装流
            bufferedInputStream = new BufferedInputStream(inputStream);

            byte[] bytes = new byte[1024];
            int readCount;
            while ((readCount = bufferedInputStream.read(bytes)) != -1) {
                System.out.print(new String(bytes, 0, readCount));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (bufferedInputStream != null) {
                try {
                    // 关闭时只需要关闭最外层的流即包装流即可
                    bufferedInputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    /**
     * 使用try-with-resources改进
     */
    private static void method2() {
        try (
                BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("io/resources/特性.txt"))
        ) {
            byte[] bytes = new byte[1024];
            int readCount;
            while ((readCount = bufferedInputStream.read(bytes)) != -1) {
                System.out.print(new String(bytes, 0, readCount));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
